package com.sudo.api._admin;

import com.sudo.common.annotation.ApiIdempotent;
import com.sudo.common.annotation.ApiAuthorization;
import com.sudo.common.utils.HttpUserInfoUtil;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.PagedGridResult;
import com.sudo.dao.admin.entity.SysRole;
import com.sudo.dao.admin.model.bo.SysRoleBO;
import com.sudo.service.admin.service.SysAutoRoleService;
import com.sudo.service.admin.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @author 为道日损 2020-04-25 23:32
 */
@Api(value = "角色接口",tags = {"角色相关的接口"})
@RestController
@RequestMapping("sysRole")
public class SysRoleController extends AdminBaseController {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysAutoRoleService sysAutoRoleService;

    @GetMapping("querySysRoleByPage")
    @ApiOperation(value = "分页查找角色",notes = "后台查找角色分页进行管理",httpMethod = "GET")
    public JsonRes querySysRoleByPage(@RequestParam Integer page,
                                      @RequestParam Integer pageSize,
                                      @RequestParam String roleCodeOrName) {
        PagedGridResult gridResult = sysRoleService.querySysRoleByPage(page, pageSize,roleCodeOrName);
        return JsonRes.ok(gridResult);
    }

    @GetMapping("getSysRoleByRoleCode")
    @ApiOperation(value = "查找一个角色",notes = "查找角色进行管理，查看或修改",httpMethod = "GET")
    public JsonRes getSysRoleByRoleCode(@RequestParam String roleCode) {
        SysRole sysRole = sysRoleService.getSysRoleByRoleCode(roleCode);
        return JsonRes.ok(sysRole);
    }

    @ApiIdempotent
    @ApiAuthorization(menu = "roleRun",button = "update")
    @PostMapping("updateSysRoleByCode")
    @ApiOperation(value = "修改一个角色",notes = "根据角色code修改当前角色",httpMethod = "POST")
    public JsonRes updateSysRoleByCode(@RequestBody @Valid SysRoleBO sysRoleBO,
                                     BindingResult result,
                                     HttpServletRequest request) {
        if (result.hasErrors()) {
            return JsonRes.errorMsg(getFirstError(result));
        }
        String sessionUser = HttpUserInfoUtil.getSessionUser(request);

        if (superAdmin(sysRoleBO.getRoleCode())) {
            return JsonRes.errorMsg("禁止修改超级管理员");
        }
        if (!superName(sessionUser)) {
            return JsonRes.errorMsg("只允许超级管理员操作");
        }
        Integer affectCount = sysRoleService.updateSysRoleByCode(sessionUser ,sysRoleBO);
        return JsonRes.judge(affectCount,"修改角色成功","修改角色失败");
    }

    @ApiIdempotent
    @ApiAuthorization(menu = "roleRun",button = "delete")
    @PostMapping("deleteSysRoleByCode")
    @ApiOperation(value = "删除一个角色",notes = "根据角色Code删除当前角色",httpMethod = "POST")
    public JsonRes deleteSysRoleByCode(@RequestParam("roleCode") String roleCode,
                                     HttpServletRequest request) {
        String sessionUser = HttpUserInfoUtil.getSessionUser(request);
        if (superAdmin(roleCode)) {
            return JsonRes.errorMsg("禁止删除超级管理员");
        }
        if (!superName(sessionUser)) {
            return JsonRes.errorMsg("只允许超级管理员操作");
        }
        int userCount = sysRoleService.getUserCountByRoleCode(roleCode);
        if (userCount > 0) {
            return JsonRes.errorMsg("该角色下尚有" + userCount + "个用户，请先移除用户");
        }
        int setupRoleCount = sysAutoRoleService.getCountBySetupRole(roleCode);
        if (setupRoleCount > 0) {
            return JsonRes.errorMsg("角色自动化中尚有" + setupRoleCount + "个用户以该角色为【设定角色】，请先移除");
        }
        int expiryRoleCount = sysAutoRoleService.getCountByExpiryRole(roleCode);
        if (expiryRoleCount > 0) {
            return JsonRes.errorMsg("角色自动化中尚有" + expiryRoleCount + "个用户以该角色为【过期角色】，请先移除");
        }
        int affectCount = sysRoleService.deleteSysRoleByRoleCode(roleCode);
        return JsonRes.judge(affectCount,"删除角色成功","删除角色失败");
    }

    @GetMapping("getAllSysRoleCodeAndNameByStatus")
    @ApiOperation(value = "获取所有角色名称和代码",notes = "获取所有角色名称和代码",httpMethod = "GET")
    public JsonRes getAllSysRoleCodeAndNameByStatus(@RequestParam("status") String status) {
        List<SysRole> sysRole = sysRoleService.getAllSysRoleCodeAndNameWithoutSuperByStatus(status);
        return JsonRes.ok(sysRole);
    }

    @GetMapping("getSimpleRoleByPage")
    @ApiOperation(value = "分页获取所有角色简单信息",notes = "分页获取所有角色简单信息",httpMethod = "GET")
    public JsonRes getSimpleRoleByPage(@RequestParam Integer page,
                                       @RequestParam Integer pageSize,
                                       @RequestParam String status) {
        PagedGridResult gridResult = sysRoleService.getSimpleRoleByPage(page,pageSize,status);
        return JsonRes.ok(gridResult);
    }

    @GetMapping("getAllSysRole")
    @ApiOperation(value = "获取所有角色名称和代码和状态(排除超级管理员)",notes = "获取所有角色名称和代码和状态(排除超级管理员)",httpMethod = "GET")
    public JsonRes getAllSysRole() {
        List<SysRole> sysRoleList = sysRoleService.getAllSysRoleWithoutSuper();
        return JsonRes.ok(sysRoleList);
    }

    @ApiIdempotent
    @ApiAuthorization(menu = "roleRun",button = "add")
    @PostMapping("addSysRole")
    @ApiOperation(value = "添加角色",notes = "添加角色",httpMethod = "POST")
    public JsonRes addSysRole(@RequestBody @Valid SysRoleBO sysRoleBO,
                              BindingResult result,
                              HttpServletRequest request) {
        if (result.hasErrors()) {
            return JsonRes.errorMsg(getFirstError(result));
        }
        String sessionUser = HttpUserInfoUtil.getSessionUser(request);
        if (!superName(sessionUser)) {
            return JsonRes.errorMsg("只允许超级管理员操作");
        }
        //判断角色code是否已经存在
        SysRole oldSysRole = sysRoleService.getSysRoleByRoleCode(sysRoleBO.getRoleCode());
        if (null != oldSysRole) {
            return JsonRes.errorMsg("角色代码已存在，请重新添加");
        }
        int affectCount = sysRoleService.addSysRole(sysRoleBO,sessionUser);
        return JsonRes.judge(affectCount,"新增角色成功","新增角色失败");
    }
}
